package com.mvcframework.testffmpeg2;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    /**
     * Environment.getExternalStorageDirectory()得到：“、mnt/sdcard” 即找到了sd卡的根目录
     */
    private String PATH = Environment.getExternalStorageDirectory().toString() + "/Android_Test";

    long nativeObj = 0;


    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.inject(this);

        // Example of a call to a native method
        TextView tv = findViewById(R.id.sample_text);
        tv.setText(stringFromJNI());
        tv.setText(String.format("" +
                        "ffmpeg version:    %s \n" +
                        "support H264:      %s \n" +
                        "support H265:      %s \n",
                        ffmpegVersion(),
                        initH264()==true?"yes":"false",
                        initH265()==true?"yes":"false"));

        if (isStoragePermissionGranted()) {
            File directory = new File(PATH);
            File[] files = directory.listFiles();
            Log.i(TAG, PATH + " files : " + (files == null ? null : files.length));
        }
    }


    @OnClick({R.id.btn_copy_test_file, R.id.btn_decoder_pure_h264, R.id.btn_decoder_pure_hevc,
            R.id.btn_create, R.id.btn_create2, R.id.btn_decode, R.id.btn_destroy})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_copy_test_file: {
                createTestFolder();

                Toast.makeText(MainActivity.this, "btn_copy_test_file", Toast.LENGTH_SHORT).show();

                FileUtils.getInstance(this).copyAssetsToSD("",new File(PATH).getName()).setFileOperateCallback(new FileUtils.FileOperateCallback() {
                    @Override
                    public void onSuccess() {
                        // TODO: 文件复制成功时，主线程回调
                        Toast.makeText(MainActivity.this, "copy test file success", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFailed(String error) {
                        // TODO: 文件复制失败时，主线程回调
                        Toast.makeText(MainActivity.this, "copy test file failed", Toast.LENGTH_SHORT).show();
                    }
                });


                break;
            }
            case R.id.btn_decoder_pure_h264: {
                boolean res = decoderPure(true);
                Toast.makeText(this, "decoderPure res = " + res, Toast.LENGTH_SHORT).show();
                break;
            }

            case R.id.btn_decoder_pure_hevc: {
                boolean res = decoderPure(false);
                Toast.makeText(this, "decoderClass res = " + res, Toast.LENGTH_SHORT).show();
                break;
            }

            case R.id.btn_create: {
                nativeObj = createNativeDecoder(0);
                Toast.makeText(this, "create " + nativeObj, Toast.LENGTH_SHORT).show();
                break;
            }

            case R.id.btn_create2: {
                nativeObj = createNativeDecoder(1);
                Toast.makeText(this, "create " + nativeObj, Toast.LENGTH_SHORT).show();
                break;
            }

            case R.id.btn_decode: {

                //创建基于文件的输入流
                try {
                    String inPath = Environment.getExternalStorageDirectory()+"/Android_Test/bigbuckbunny_480x272.yuv";
                    String outPath = Environment.getExternalStorageDirectory()+"/Android_Test/bigbuckbunny_480x272_jni.yuv";
                    File inFile =new File(inPath);
                    File outFile = new File(outPath);
                    InputStream is = new FileInputStream(inFile);
                    FileOutputStream fos = new FileOutputStream(outFile);
                    byte[] buffer = new byte[4096];
                    int byteCount;
                    while ((byteCount = is.read(buffer)) != -1) {
                        fos.write(buffer, 0, byteCount);
                    }
                    fos.flush();

                    is.close();
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    Toast.makeText(this, "decode" , Toast.LENGTH_SHORT).show();
                }
                break;
            }

            case R.id.btn_destroy: {
                Toast.makeText(this, "destroy " + nativeObj, Toast.LENGTH_SHORT).show();
                destroyNativeDecoder(nativeObj);

                break;
            }

        }
    }

    private boolean isStoragePermissionGranted() {
        if (Build.VERSION.SDK_INT >= 23) {
            final Context context = getApplicationContext();
            int readPermissionCheck = ContextCompat.checkSelfPermission(context,
                    Manifest.permission.READ_EXTERNAL_STORAGE);
            int writePermissionCheck = ContextCompat.checkSelfPermission(context,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (readPermissionCheck == PackageManager.PERMISSION_GRANTED
                    && writePermissionCheck == PackageManager.PERMISSION_GRANTED) {
                Log.v(TAG, "Permission is granted");
                return true;
            } else {
                Log.v(TAG, "Permission is revoked");
                ActivityCompat.requestPermissions(this, new String[]{
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                return false;
            }
        } else { //permission is automatically granted on sdk<23 upon installation
            Log.v(TAG, "Permission is granted");
            return true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.v(TAG, "onRequestPermissionsResult requestCode ： " + requestCode
                + " Permission: " + permissions[0] + " was " + grantResults[0]
                + " Permission: " + permissions[1] + " was " + grantResults[1]
        );
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            //resume tasks needing this permission
            File directory = new File(PATH + "/Android_Test");
            File[] files = directory.listFiles();
            Log.i(TAG, "After PERMISSION_GRANTED files : " + (files == null ? null : files.length));
        }
    }

    private void createTestFolder() {
        File f = new File(PATH);

        if(f.exists() == false) {
            // 创建文件夹，如果父文件夹不存在，就会创建父文件夹
            f.mkdirs();
        }
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();
    public native String ffmpegVersion();
    public native boolean initH264();
    public native boolean initH265();
    public native boolean decoderPure(boolean isH264);
    public static native long createNativeDecoder(int type);
    public static native void destroyNativeDecoder(long nativeObj);
}
